package com.orangelife.mobile.web;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.net.Uri;
import android.text.TextUtils;

import com.common.jump.PayJumper;
import com.common.sp.CommSp2;
import com.common.sp.SharedPreferUtil;
import com.common.sp.UserSp;
import com.common.util.OrangePhoneUtil;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.StringUtil;
import com.curry.android.util.SystemInfoUtil;
import com.curry.android.util.ToastHelper;
import com.datatrack.DataTrack;
import com.orangelife.arenasdk.main.Arena;
import com.orangelife.arenasdk.main.EventCallback;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.constants.WebViewURL;
import com.orangelife.mobile.download.ImageDownloader;
import com.orangelife.mobile.goodsOrder.biz.OrderBiz;
import com.orangelife.mobile.main.biz.JumpUtil;
import com.orangelife.mobile.pay.biz.PayHttpBiz;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.util.LogE;
import com.thirdsdk.umeng.UmShareBiz;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

/**
 * 通用javascript的回调函数的实现
 * <p/>
 * Created by 吴格非 on 2016-8-24.
 * <p/>
 *
 * @author 吴格非
 * @since v1.0.0
 */
public class CommonJs {

    private Activity mContext;
    protected WebHandler mHandler;


    public CommonJs(Activity context) {
        this.mContext = context;
    }

    public void setHandler(WebHandler handler) {
        this.mHandler = handler;
    }

    @android.webkit.JavascriptInterface
    public void share(String url) {/*签到引导遮罩页的地址*/
        jumpURL(url);
    }

    @android.webkit.JavascriptInterface
    public void openurl(String url) {
        jumpURL(url);
    }

    @android.webkit.JavascriptInterface
    public void onFinished() {/*签到完成*/
        if (checkHandler()) {
            mHandler.send(WebWhat.SHOW_TITLE1);
        }
    }

    private void jumpToPay(String[] orderIDs, String totalCost, String orderContent, String outtradeno, String point, String paidMethod, String orderType) {
         /*社区活动的支付*/
        PayJumper.jumpToUsersPaid(mContext, orderIDs[0], paidMethod, totalCost, orderContent, outtradeno, point, orderType);
            /*所有订单支付的类都要调用ExitApplication.addPaidActivity()，以保证在支付界面可以回退，在支付结果界面可以被统一关闭*/
        ExitApplication.getInstance().addPaidActivity(mContext);
    }

    private void requestPayFree(String outtradeno, final String orderID) {
        mHandler.send(WebWhat.SHOW_LOADING);
        PayHttpBiz.payWithWallet(outtradeno, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                mHandler.send(WebWhat.HIDE_LOADING);
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    ToastHelper.getInstance()._toast("参与成功");
                    mHandler.send(WebWhat.JUMP, WebViewURL.COMMUNITY_ACTIVITY_ORDER_DETAIL + "?orderID=" + orderID + "&accessToken=" + UserSp.getAccessToken());
                } else {
                    ToastHelper.getInstance()._toast("参与失败");
                }
            }
        });
    }

    private void commonPay(String[] orderIDs, String totalCost, String orderContent, String outtradeno, String point, String couponCost, String paidMethod, String orderType) {
        if (orderIDs != null && orderIDs.length > 0) {/*支付*/
            if (isFree(totalCost)) {
                String orderID = orderIDs[0];
                requestPayFree(outtradeno, orderID);
            } else {
                jumpToPay(orderIDs, totalCost, orderContent, outtradeno, point, paidMethod, orderType);
            }
        } else {
            ToastHelper.getInstance()._toast("订单号为空");
        }
    }

    @android.webkit.JavascriptInterface
    public void paid(String[] orderIDs, String totalCost, String orderContent, String outtradeno, String point, String couponCost) {
        commonPay(orderIDs, totalCost, orderContent, outtradeno, point, couponCost, PaymentModule.COMMUNITY_ACTIVITY, null);
    }

    @android.webkit.JavascriptInterface
    public void paid(String[] orderIDs, String totalCost, String orderContent, String outtradeno, String point, String couponCost, String paidMethod) {
        commonPay(orderIDs, totalCost, orderContent, outtradeno, point, couponCost, paidMethod, null);
    }

    @android.webkit.JavascriptInterface
    public void paid(String[] orderIDs, String totalCost, String orderContent, String outtradeno, String point, String couponCost, String paidMethod, String orderType) {
        commonPay(orderIDs, totalCost, orderContent, outtradeno, point, couponCost, paidMethod, orderType);
    }

    @android.webkit.JavascriptInterface
    public void paid(String[] orderIDs, String totalCost, String orderContent) {/*支付*/
        if (orderIDs != null && orderIDs.length > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("totalCost", totalCost);
            map.put("orderID", orderIDs[0]);
            map.put("orderType", PaymentModule.COMMUNITY_ACTIVITY
            );
            OrderBiz.payOrder(map, mContext, orderContent);
        } else {
            ToastHelper.getInstance()._toast("订单号为空");
        }
    }

//    @android.webkit.JavascriptInterface
//    public void paid(String[] orderIDs, String totalCost, String orderContent, String orderType) {/*支付*/
//        if (orderIDs != null && orderIDs.length > 0) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("totalCost", totalCost);
//            map.put("orderID", orderIDs[0]);
//            map.put("orderType", orderType
//            );
//            OrderBiz.payOrder(map, mContext, orderContent);
//        } else {
//            ToastHelper.getInstance()._toast("订单号为空");
//        }
//    }

    /** 是否免费 */
    private boolean isFree(String totalCost) {
        try {
            int iTotalCost = Integer.parseInt(totalCost);
            if (iTotalCost == 0) {
                return true;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return false;
    }

    @android.webkit.JavascriptInterface
    public void identityAuthentication(String sendFunctionJson) {
        if (checkHandler()) {
            mHandler.send(WebWhat.JUMP_CERT);
            mHandler.send(WebWhat.SEND_FUNCTION_JSON, sendFunctionJson);
        }
    }

    @android.webkit.JavascriptInterface
    public String getcommID() {/*获取小区ID*/
        return CommSp2.getCommID();
    }

    @android.webkit.JavascriptInterface
    public String getcommName() {/*获取小区ID*/
        return CommSp2.getCommName();
    }

    @android.webkit.JavascriptInterface
    public String getUserInfo() {/*获取小区ID*/
        String json = "{\"userName\":\"" + UserSp.getNickname() + "\",\"userPhone\":\"" + UserSp.getRegPhone() + "\",\"commID\":\"" + CommSp2.getCommID() + "\",\"commName\":\"" + CommSp2.getCommName() + "\",\"userID\":\"" + UserSp.getLoginID() + "\",\"versionName\":\"" + SystemInfoUtil.getVersionName(mContext) + "\",\"userIcon\":\"" + UserSp.getProtraitImg() + "\"}";
        return json;
    }

    @android.webkit.JavascriptInterface
    public String getAccessToken() {/*获取token*/
        return UserSp.getAccessToken();
    }

    @android.webkit.JavascriptInterface
    public void share2(String title, String content, String url) {/*友盟分享*/
        new UmShareBiz(mContext).share(title, content, url, "");
    }

    @android.webkit.JavascriptInterface
    public void setActTitle(String title) {/*设置标题*/
        /*不能再javascript的回调函数中直接操作View，否则会导致整个界面无法显示出来*/
        if (checkHandler()) {
            mHandler.send(WebWhat.SHOW_TITLE1, title);
        }
    }

    @android.webkit.JavascriptInterface
    public void setActTitleMore(boolean isShowRight) {
        if (isShowRight) {
            mHandler.send(WebWhat.SHOW_RIGHT_ICON);
        } else {
            mHandler.send(WebWhat.HIDE_RIGHT_ICON);
        }
    }

    @android.webkit.JavascriptInterface
    public void setActSellTitle(String title, boolean isShowTitle2) {
        if (checkHandler()) {
            mHandler.obtainMessage(WebWhat.SHOW_TITLE2, title).sendToTarget();
        }
    }

    @android.webkit.JavascriptInterface
    public void saveImg(String imgurl) {/*长按保存图片*/
        ImageDownloader.loadImage(imgurl, null, true, mHandler);
    }

    @android.webkit.JavascriptInterface
    public void copyAddress(String address) {/*复制到剪贴板*/
        ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Activity.CLIPBOARD_SERVICE);
        clipboard.setPrimaryClip(ClipData.newPlainText("text", address));
        ToastHelper.getInstance()._toast("地址已经复制到剪贴板");
    }

    @android.webkit.JavascriptInterface
    public void telme() {/*拨打橙子客服*/
        OrangePhoneUtil.callCustomerService2(mContext);
    }

    private void jumpURL(String url) {
        Uri uri = Uri.parse(url);
        if (uri.getScheme().equals("orangelife")
                && uri.getHost().equals("www.com")) {
            JumpUtil.jumpActivity(mContext, url, true);
        } else {
            if (checkHandler()) {
                mHandler.obtainMessage(WebWhat.LOAD_URL, url).sendToTarget();
            }
        }
    }

    protected boolean checkHandler() {
        if (mHandler != null) {
            return true;
        } else {
            LogE.E(CommonJs.class.getSimpleName(), "Hanlder 为空");
        }
        return false;
    }

    /*================================================*/

    @android.webkit.JavascriptInterface
    public void arenaInit(String functionName, String seqID, String gameID) {/*初始化游戏SDK*/
        Arena.getInstance().init(functionName, seqID, gameID, UserSp.getAccessToken(), CommSp2.getCommID(), SystemInfoUtil.getVersionName(mContext), new EventCallback() {
            @Override
            public void onFinish(String functionName, String seqID, String result) {
                sendFunction(functionName, seqID, result);
            }
        });
    }

    @android.webkit.JavascriptInterface
    public void arenaEvent(String functionName, String seqID, String json) {/*提交游戏数据*/
        Arena.getInstance().event(functionName, seqID, json, new EventCallback() {
            @Override
            public void onFinish(String functionName, String seqID, String result) {
                sendFunction(functionName, seqID, result);
            }
        });
    }

    @android.webkit.JavascriptInterface
    public void arenaRank(String functionName, String seqID, String json) {/*排行榜*/
        Arena.getInstance().rank(functionName, seqID, json, new EventCallback() {
            @Override
            public void onFinish(String functionName, String seqID, String result) {
                sendFunction(functionName, seqID, result);
            }
        });
    }

    @android.webkit.JavascriptInterface
    public String arenaUserInfo() {/*获取用户信息*/
        String nickName = SharedPreferUtil.getInstance().getString("nickname", "");
        if (StringUtil.isBlank(nickName)) {
            nickName = SharedPreferUtil.getInstance().getString("phone", "");
            if (StringUtil.isBlank(nickName)) {
                nickName = "user" + System.currentTimeMillis();
            } else {
                nickName = nickName.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            }
        }
        return "{\"userName\":\"" + nickName + ",\"userIcon\":\"" + UserSp.getProtraitImg() + "\"}";
    }

    private void sendFunction(String functionName, String seqID, String result) {
        if (checkHandler()) {
            LogE.E("result = " + result);
            String js = "javascript:" + functionName + "('" + seqID + "','" + result + "')";
            mHandler.send(WebWhat.SEND_FUNCTION_JSON2, js);
        }
    }

    @android.webkit.JavascriptInterface
    public void clickTrack(String json) {
        String str = json.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
        try {
            DataTrack.clickTrack(URLDecoder.decode(str, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @android.webkit.JavascriptInterface
    public void browseTrack(String json) {
        String str = json.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
        try {
            DataTrack.browseTrack(URLDecoder.decode(str, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @android.webkit.JavascriptInterface
    public void updateApp(String url) {
        if (mContext != null) {
            if (!StringUtil.isBlank(url)) {
                ((WebActivity) mContext).myBinder.apkUrl = url;
                ((WebActivity) mContext).myBinder.setContext(mContext);
                ((WebActivity) mContext).myBinder.functionUpdate();
            } else {
                ((WebActivity) mContext).requestUpdateVersion(mContext);
            }
        } else {
            ToastHelper.getInstance()._toast("下载失败,请重新进入页面再次尝试。");
        }
    }


}
